package models

import (
	"errors"
	"log"
	"regexp"
)

type User struct {
	Id              int    `xorm:"not null pk autoincr comment('自增主键') INT(11)"`
	Type            string `xorm:"default '4' comment('用户类别，1：运管，2：驾校，3：教练，4：学员，5:考核员 6:安全员') ENUM('1','2','3','4','5','6')" form:"type"`
	Password        string `xorm:"not null comment('用户密码使用MD5加密存储') CHAR(32)" form:"password"`
	Name            string `form:"name" xorm:"not null comment('姓名') VARCHAR(16)"`
	Sex             string `form:"sex" xorm:"default '1' comment('用户性别，1：男性， 2：女性') ENUM('1','2')"`
	Nation          string `form:"nation" xorm:"default '' comment('民族') VARCHAR(16)"`
	Phone           string `form:"phone"  xorm:"comment('手机号码，联系方式') unique VARCHAR(16)"`
	Mail            string `xorm:"default '' comment('用户电子邮箱地址') VARCHAR(64)" form:"mail"`
	Address         string `form:"address" xorm:"default '' comment('用户办公/家庭地址') VARCHAR(512)"`
	Nationality     string `form:"nationality" xorm:"not null default '中国' comment('国籍') VARCHAR(32)"`
	District        string `xorm:"comment('区县行政区划代码') VARCHAR(6)" form:"district"`
	IdType          string `xorm:"default '1' comment('证件类型 1:身份证， 2:护照， 3:军官证， 4:其他') ENUM('1','2','3','4')" form:"id_type"`
	IdNumber        string `xorm:"not null comment('证件号') VARCHAR(32)" form:"id_number"`
	Native          string `xorm:"not null comment('籍贯') VARCHAR(6)" form:"native"`
	Sid             int    `xorm:"default 0 comment('学校id') INT(10)" form:"sid"`
	Cardid          string `xorm:"not null default '' comment('身份证ID号') VARCHAR(16)" form:"card_id"`
	Isused          string `xorm:"default '1' comment('1 正在使用   0已删除') ENUM('0','1')"`
	Remark          string `xorm:"comment('已删除的学员手机号') VARCHAR(16)"`
	Isotherprovince string `xorm:"default '0' comment('') ENUM('0','1')" form:"isotherprovince"`
	Birthday        string `xorm:"VARCHAR(512)" form:"birthday"`
	Icaddress       string `xorm:"VARCHAR(512)" form:"icaddress"`
	ReidNumber      string `xorm:"VARCHAR(32)"`
	GroupId         int    `xorm:"-" form:"group_id"`
	CardUrl         string `xorm:"-"  form:"card_url"`
}

// GetUserByPhone 通过手机号获取用户信息
func (u *User) GetUserByPhone(phone string) (bool, error) {
	return engine.Table("dts_user").Where("phone=? and isused= ?", phone, "1").Get(u)
}

// CheckExitUserByNum 通过身份证号查看该学员是否存在
func (u *User) CheckExitUserByNum(num, userType string) (bool, error) {
	return engine.Table("dts_user").Where("id_number=?  and type= ?", num, userType).Exist()
}

func (u *User) Edit(who ...string) bool {
	if _, err := engine.ID(u.Id).Cols(who...).Update(u); err != nil {
		return false
	}
	return true
}

func (u *User) CheckData(types int) (err error) {
	if u.Phone != "" && u.HasPhone(types) {
		return errors.New("手机号已存在")
	}
	if u.IdNumber != "" && u.HasIdNumber(types) {
		return errors.New("身份证号已存在")
	}
	if _, err = regexp.MatchString(`^(\d{17})([0-9]|X)$`, u.IdNumber); err != nil {
		return errors.New("身份证号码错误")
	}
	return nil
}

func (u *User) HasPhone(types int) bool {
	if types == 1 {
		has, err := engine.Table("dts_user").Where("phone = ? && isused=?", u.Phone, "1").Exist()
		if has && err == nil {
			return true
		} else {
			return false
		}
	} else {
		user := new(User)
		if _, err := engine.Table("dts_user").Where("phone = ? && isused=?", u.Phone, "1").Get(user); err != nil {
			return false
		} else {
			//phone 已经重复
			if u.Id == user.Id {
				//phone 没有变化
				return false
			} else {
				//已经存在该phone了
				return true
			}
		}
	}
}

func (u *User) HasIdNumber(types int) bool {
	//id_number := strings.Replace(strings.Replace(c.IdNumber, "t", "", -1), "t", "", -1)
	if types == 1 {
		has, err := engine.Table("dts_user").Where("id_number = ? and isused=? and type = ?", u.IdNumber, "1", u.Type).Exist()
		if has && err == nil {
			return true
		} else {
			return false
		}
	} else {
		user := new(User)
		if _, err := engine.Table("dts_user").Where("id_number = ? and isused=? and type = ?", u.IdNumber, "1", u.Type).Get(user); err != nil {
			return false
		} else {
			//如果编辑的id_number 已经重复
			if u.Id == user.Id {
				//id_number 没有变化
				return false
			} else {
				//已经存在该id_number了
				return true
			}
		}
	}
}

func (u *User) GetUserById(id int) (list *User, err error) {
	list = new(User)
	if _, err = engine.Table("dts_user").Where("id = ? and isused=?", id, "1").Get(list); err != nil {
		log.Println(err)
		return list, err
	}
	return list, nil
}
